<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;
use app\model\Config as ConfigModel;

class Config extends Base
{

    /**
     * 显示指定的资源
     *
     * @param  int  $item
     * @return \think\Response
     */
    public function read($item)
    {
        $key = 'app.config.'.$item;
        $config_item = config($key);
        $title = config('app.config.title_'.$item);
        if(!$config_item){
            return  $this->create([],'参数不合法！',400);
        }
        $data = ConfigModel::where('key',$item)->find();
        if($data){
            $result = json_decode($data['value']);
        }else{
            $create_data = [
                'title' => $title,
                'key' => $item,
                'value' => json_encode($config_item)
            ];
            ConfigModel::create($create_data);
            $result = $config_item;
        }
        return $this->create($result,'请求'.$title.'数据成功');
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $item
     * @return \think\Response
     */
    public function update(Request $request, $item)
    {
        $key = 'app.config.'.$item;
        $config_item = config($key);
        if(!$config_item){
            return  $this->create([],'参数不合法！',400);
        }
        $param = $request->put();
        $data['value'] = json_encode($param);
        $row = ConfigModel::where('key',$item)->find();
        if($row && $row->save($data)){
            return  $this->create([],'修改成功');
        }else{
            return  $this->create([],'修改失败',400);
        }
    }

}
